package com.lushuai.jiubeidanci.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.lushuai.jiubeidanci.LoginActivity;
import com.lushuai.jiubeidanci.R;
import com.lushuai.jiubeidanci.dao.UserDao;
import com.lushuai.jiubeidanci.model.User;

public class ProfileDetailActivity extends AppCompatActivity {
    private ImageView ivAvatar;
    private TextView tvNickname;
    private TextView tvPhone;
    private UserDao userDao;
    private User currentUser;
    private static final int REQUEST_CHANGE_AVATAR = 1001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile_detail);

        userDao = new UserDao(this);
        initViews();
        loadUserData();
        setupClickListeners();
    }

    private void initViews() {
        ivAvatar = findViewById(R.id.iv_avatar);
        tvNickname = findViewById(R.id.tv_nickname);
        tvPhone = findViewById(R.id.tv_phone);
    }

    private void loadUserData() {
        // 从Intent获取用户ID
        long userId = getIntent().getLongExtra("user_id", -1);
        if (userId == -1) {
            // 如果Intent中没有，则从SharedPreferences获取
            SharedPreferences sp = getSharedPreferences("user_info", MODE_PRIVATE);
            userId = sp.getLong("user_id", -1);
        }
        
        if (userId != -1) {
            currentUser = userDao.getUserById(userId);
            if (currentUser != null) {
                // 设置昵称
                tvNickname.setText(currentUser.getNickname());
                
                // 设置手机号
                String phone = currentUser.getPhone();
                tvPhone.setText(phone != null ? phone : "待补充");
                
                // 设置头像（如果有）
                if (currentUser.getAvatarUrl() != null) {
                    // TODO: 使用图片加载库加载头像
                    // Glide.with(this).load(currentUser.getAvatarUrl()).into(ivAvatar);
                }
            }
        }
    }

    private void setupClickListeners() {
        // 返回按钮
        findViewById(R.id.btn_back).setOnClickListener(v -> finish());

        // 头像修改
        findViewById(R.id.iv_avatar).setOnClickListener(v -> {
            Intent intent = new Intent(Intent.ACTION_PICK);
            intent.setType("image/*");
            startActivityForResult(intent, REQUEST_CHANGE_AVATAR);
        });

        // 昵称修改
        findViewById(R.id.layout_nickname).setOnClickListener(v -> showEditNicknameDialog());

        // 手机号绑定
        findViewById(R.id.layout_phone).setOnClickListener(v -> showBindPhoneDialog());

        // 修改密码
        findViewById(R.id.layout_change_password).setOnClickListener(v -> showChangePasswordDialog());

        // 社交账号绑定
        findViewById(R.id.layout_qq).setOnClickListener(v -> 
            Toast.makeText(this, "QQ绑定功能开发中", Toast.LENGTH_SHORT).show());
        findViewById(R.id.layout_wechat).setOnClickListener(v -> 
            Toast.makeText(this, "微信绑定功能开发中", Toast.LENGTH_SHORT).show());
        findViewById(R.id.layout_weibo).setOnClickListener(v -> 
            Toast.makeText(this, "微博绑定功能开发中", Toast.LENGTH_SHORT).show());

        // 退出登录
        findViewById(R.id.btn_logout).setOnClickListener(v -> logout());
    }

    // 显示修改昵称对话框
    private void showEditNicknameDialog() {
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_edit_nickname, null);
        EditText etNickname = dialogView.findViewById(R.id.et_nickname);
        etNickname.setText(currentUser.getNickname());

        new AlertDialog.Builder(this)
            .setView(dialogView)
            .setPositiveButton("确定", (dialog, which) -> {
                String newNickname = etNickname.getText().toString().trim();
                if (!TextUtils.isEmpty(newNickname)) {
                    updateNickname(newNickname);
                }
            })
            .setNegativeButton("取消", null)
            .show();
    }

    // 更新昵称
    private void updateNickname(String newNickname) {
        currentUser.setNickname(newNickname);
        if (userDao.update(currentUser) > 0) {
            tvNickname.setText(newNickname);
            Toast.makeText(this, "昵称修改成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "昵称修改失败", Toast.LENGTH_SHORT).show();
        }
    }

    // 显示绑定手机号对话框
    private void showBindPhoneDialog() {
        View dialogView = LayoutInflater.from(this)
            .inflate(R.layout.dialog_bind_phone, null);
        EditText etPhone = dialogView.findViewById(R.id.et_phone);
        EditText etCode = dialogView.findViewById(R.id.et_verification_code);
        Button btnSendCode = dialogView.findViewById(R.id.btn_send_code);

        btnSendCode.setOnClickListener(v -> {
            String phone = etPhone.getText().toString().trim();
            if (isValidPhoneNumber(phone)) {
                // TODO: 发送验证码
                Toast.makeText(this, "验证码发送功能开发中", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "请输入正确的手机号", Toast.LENGTH_SHORT).show();
            }
        });

        new AlertDialog.Builder(this)
            .setView(dialogView)
            .setPositiveButton("确定", (dialog, which) -> {
                String phone = etPhone.getText().toString().trim();
                String code = etCode.getText().toString().trim();
                if (verifyPhoneAndCode(phone, code)) {
                    bindPhone(phone);
                }
            })
            .setNegativeButton("取消", null)
            .show();
    }

    // 显示修改密码对话框
    private void showChangePasswordDialog() {
        View dialogView = LayoutInflater.from(this)
            .inflate(R.layout.dialog_change_password, null);
        EditText etOldPassword = dialogView.findViewById(R.id.et_old_password);
        EditText etNewPassword = dialogView.findViewById(R.id.et_new_password);
        EditText etConfirmPassword = dialogView.findViewById(R.id.et_confirm_password);

        new AlertDialog.Builder(this)
            .setView(dialogView)
            .setPositiveButton("确定", (dialog, which) -> {
                String oldPassword = etOldPassword.getText().toString();
                String newPassword = etNewPassword.getText().toString();
                String confirmPassword = etConfirmPassword.getText().toString();
                
                if (verifyAndUpdatePassword(oldPassword, newPassword, confirmPassword)) {
                    Toast.makeText(this, "密码修改成功", Toast.LENGTH_SHORT).show();
                    logout(); // 修改密码后需要重新登录
                }
            })
            .setNegativeButton("取消", null)
            .show();
    }

    // 验证手机号格式
    private boolean isValidPhoneNumber(String phone) {
        return phone.matches("^1[3-9]\\d{9}$");
    }

    // 验证手机号和验证码
    private boolean verifyPhoneAndCode(String phone, String code) {
        // TODO: 实现验证码验证逻辑
        return true;
    }

    // 绑定手机号
    private void bindPhone(String phone) {
        currentUser.setPhone(phone);
        if (userDao.update(currentUser) > 0) {
            tvPhone.setText(phone);
            Toast.makeText(this, "手机号绑定成功", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "手机号绑定失败", Toast.LENGTH_SHORT).show();
        }
    }

    // 验证并更新密码
    private boolean verifyAndUpdatePassword(String oldPassword, String newPassword, String confirmPassword) {
        if (!currentUser.getPassword().equals(oldPassword)) {
            Toast.makeText(this, "原密码错误", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (!newPassword.equals(confirmPassword)) {
            Toast.makeText(this, "两次输入的密码不一致", Toast.LENGTH_SHORT).show();
            return false;
        }

        currentUser.setPassword(newPassword);
        return userDao.update(currentUser) > 0;
    }

    // 退出登录
    private void logout() {
        SharedPreferences sp = getSharedPreferences("user_info", MODE_PRIVATE);
        sp.edit().clear().apply();

        Intent intent = new Intent(this, LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }
} 